package com.foucus.myfouces.MVP.View.views.Fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foucus.myfouces.Adapter.BannerPageAdapter;
import com.foucus.myfouces.Adapter.SquareNewVideoAdapter;
import com.foucus.myfouces.Adapter.SquareTitleAdapter;
import com.foucus.myfouces.Adapter.ViewpagerAdapter;
import com.foucus.myfouces.Api.GankService;
import com.foucus.myfouces.Base.BaseFragment;
import com.foucus.myfouces.Base.BaseReq;
import com.foucus.myfouces.Base.Setting;
import com.foucus.myfouces.MVP.Model.BannerResp;
import com.foucus.myfouces.MVP.Model.NewestVedioListResp;
import com.foucus.myfouces.MVP.Model.SquareVideoResp;
import com.foucus.myfouces.MVP.Presenler.IPresenler.IBannerP;
import com.foucus.myfouces.MVP.Presenler.IPresenler.INewestVideoP;
import com.foucus.myfouces.MVP.Presenler.IPresenler.ISquareVideoP;
import com.foucus.myfouces.MVP.Presenler.Presenler_class.BannerP;
import com.foucus.myfouces.MVP.Presenler.Presenler_class.NewestVideoP;
import com.foucus.myfouces.MVP.Presenler.Presenler_class.SquareVideoP;
import com.foucus.myfouces.MVP.View.IView.IHomePageFG;
import com.foucus.myfouces.R;

import com.foucus.myfouces.Resource.Banner2.CircleIndicator;
import com.foucus.myfouces.Resource.Banner2.LoopViewPager;
import com.foucus.myfouces.Resource.FullyLinearLayoutManager;
import com.foucus.myfouces.Resource.HttpUtil.ServiceFactory;
import com.foucus.myfouces.Resource.Util.GsonImpl;
import com.foucus.myfouces.Resource.Util.JsonUtil;
import com.foucus.myfouces.Resource.Util.SharedPreferencesUtil;
import com.foucus.myfouces.Resource.Util.StartActivity;
import com.foucus.myfouces.Resource.Util.Utils;
import com.foucus.myfouces.Resource.view.MyRecyclerView;
import com.foucus.myfouces.Resource.view.OnRcvScrollListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yf-06 on 2017/6/27.
 * 首页
 */

public class HomePageFg extends BaseFragment implements View.OnClickListener, IHomePageFG {


    @Bind(R.id.rcv_homepage_new_fg)
    MyRecyclerView rcv_homepage_new_fg;
    @Bind(R.id.img_back)
    ImageView img_back;
    @Bind(R.id.lly_back)
    LinearLayout lly_back;
    @Bind(R.id.tv_title_bar_title)
    TextView tv_title_bar_title;
    @Bind(R.id.img_title_bar_right)
    ImageView img_title_bar_right;
    @Bind(R.id.lly_title_bar_right)
    LinearLayout lly_title_bar_right;
    @Bind(R.id.tv_save)
    TextView tv_save;
    @Bind(R.id.rxtext_pcfl)
    PtrClassicFrameLayout rxtextPcfl;
    MyRecyclerView rcv_homepage_square_fg;
    TabLayout tably_homepage_square_fg;
    ViewPager vp_homepage_square_fg;
    ViewpagerAdapter viewpagerAdapter;
    private LoopViewPager lvp_ad;
    private CircleIndicator cindicator_dot;
    private View rootView;
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;

    private List<BannerResp.ResultBean.DataBean> bannerList;
    private List<SquareVideoResp.ResultBean.DataBean> squareVideoList;
    private List<NewestVedioListResp.ResultBean.DataBean> newestVedioList;
    private BannerPageAdapter bannerPageAdapter;
    private SquareTitleAdapter squareTitleAdapter;
    private SquareNewVideoAdapter squareNewVideoAdapter;
    private View heardview, footerview; //recycler添加头部和底部

    private IBannerP iBannerP;
    private ISquareVideoP iSquareVideoP;
    private INewestVideoP iNewestVideoP;
    boolean isLoading; //判断是否还有数据可以加载
    private boolean isFooterview = true; //判断是否到底部

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        init();
        initData();
        initRecycleview();
        Log.e("ssss", "版本号==》" + Utils.getAppVersionName(mActivity));
    }


    private void init() {
        rxtextPcfl = (PtrClassicFrameLayout) mActivity.findViewById(R.id.rxtext_pcfl);
        lly_back.setVisibility(View.GONE);
        tv_title_bar_title.setText("焦距");
        lly_title_bar_right.setVisibility(View.VISIBLE);
        bannerList = new ArrayList<>();
        squareVideoList = new ArrayList<>();
        newestVedioList = new ArrayList<>();
        rxtextPcfl.setLastUpdateTimeRelateObject(this);
        //解决刷新控件和viewpage滑动冲突
        rxtextPcfl.disableWhenHorizontalMove(true);
        rxtextPcfl.autoRefresh();

        rxtextPcfl.setPtrHandler(new PtrDefaultHandler() {
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return !canChildScrollUp(rcv_homepage_fg);
//            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                Log.e("ssss", "加载");
                iBannerP.getBannerList("1");
            }
        });


    }

    private void initData() {
        iBannerP = new BannerP(mActivity, this);
        iBannerP.getBannerList("1");


        iSquareVideoP = new SquareVideoP(mActivity, this);

        iNewestVideoP = new NewestVideoP(mActivity, this);

    }

    private void initRecycleview() {

        rcv_homepage_new_fg.setLayoutManager(new GridLayoutManager(mActivity, 1));
        // RecyclerView底部加载view
        footerview = LayoutInflater.from(mActivity).inflate(R.layout.footerview, null);

        // RecyclerView头部view
        heardview = LayoutInflater.from(mActivity).inflate(R.layout.heardview, null);

        rcv_homepage_square_fg = (MyRecyclerView) heardview.findViewById(R.id.rcv_homepage_square_fg);
        rcv_homepage_square_fg.setLayoutManager(new FullyLinearLayoutManager(heardview.getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rcv_homepage_square_fg.setFocusable(false);
        lvp_ad = (LoopViewPager) heardview.findViewById(R.id.lvp_ad);
        cindicator_dot = (CircleIndicator) heardview.findViewById(R.id.cindicator_dot);
        squareTitleAdapter = new SquareTitleAdapter(mActivity, squareVideoList);
        rcv_homepage_square_fg.setAdapter(squareTitleAdapter);


        tably_homepage_square_fg = (TabLayout) heardview.findViewById(R.id.tably_homepage_square_fg);
        vp_homepage_square_fg = (ViewPager) heardview.findViewById(R.id.vp_homepage_square_fg);
        viewpagerAdapter = new ViewpagerAdapter(getChildFragmentManager(), mActivity);
        vp_homepage_square_fg.setOffscreenPageLimit(0);
        vp_homepage_square_fg.setAdapter(viewpagerAdapter);
        tably_homepage_square_fg.setupWithViewPager(vp_homepage_square_fg);
        vp_homepage_square_fg.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {


            }

            @Override
            public void onPageSelected(int i) {
                switch (i) {
                    case 0:

                        break;
                    case 1:

                        break;
                    case 2:

                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        /**
         *  监听recyclerView是否到底部
         */
        rcv_homepage_new_fg.addOnScrollListener(new OnRcvScrollListener(rcv_homepage_new_fg) {
            @Override
            public void onBottom() {
                super.onBottom();
                if (!isLoading) {
                    isLoading = true;
                    iNewestVideoP.getNewestVideoList(MORE);
                    Log.e("ssss", "到达底部");
                }
            }

            @Override
            public void onScrollldistance(int distance, int position) {
                super.onScrollldistance(distance, position);
                if (position == 0) {
//                    if (distance > 300) {
//                        floatingActionButton.setVisibility(View.VISIBLE);
//                    } else {
//                        floatingActionButton.setVisibility(View.GONE);
//                    }
                }
            }
        });
    }


    @OnClick({R.id.lly_title_bar_right})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lly_title_bar_right:

                break;
        }
    }

    /**
     * 获取广告栏数据
     */
    @Override
    public void onBannerCompleted(List<BannerResp.ResultBean.DataBean> bannerList1) {
        bannerList.clear();
        bannerList.addAll(bannerList1);
        initBanner();
        iSquareVideoP.getSquareVideo("0");
    }

    /**
     * 获取广场数据（精选推荐、热门夯作）
     */

    @Override
    public void onSquareVideoCompleted(List<SquareVideoResp.ResultBean.DataBean> dataBeanList) {
        squareVideoList.clear();
        squareVideoList.addAll(dataBeanList);
        squareTitleAdapter.notifyDataSetChanged();

        iNewestVideoP.getNewestVideoList(REFRESH);
    }

    /**
     * 获取最新作品
     */
    @Override
    public void onNewestVideoCompleted(List<NewestVedioListResp.ResultBean.DataBean> dataBeen, int total) {
        newestVedioList.clear();
        newestVedioList.addAll(dataBeen);
        if (newestVedioList.size() < total) {
            isLoading = false;
        }
        setAdapter1(total);
        rxtextPcfl.refreshComplete();
    }

    private void initBanner() {
        if (bannerPageAdapter == null) {
            bannerPageAdapter = new BannerPageAdapter(mActivity, bannerList);
            lvp_ad.setAdapter(bannerPageAdapter);//广告栏的适配器
            cindicator_dot.setViewPager("homepagefg", lvp_ad);
        } else {
            bannerPageAdapter.notifyDataSetChanged();
        }

    }

    private void setAdapter1(int total) {
        if (squareNewVideoAdapter == null) {

            squareNewVideoAdapter = new SquareNewVideoAdapter(newestVedioList, mActivity, total);
            rcv_homepage_new_fg.setAdapter(squareNewVideoAdapter);
            squareNewVideoAdapter.addHeaderView(heardview);
            squareNewVideoAdapter.addFooterView(footerview);
            squareNewVideoAdapter.notifyDataSetChanged();

        } else {
            if (!isFooterview) {
                Log.e("ssss", "添加底部view");
                squareNewVideoAdapter.addFooterView(footerview);
                squareNewVideoAdapter.notifyDataSetChanged();
            }
            //当底部没数据时 将添加到底部的view删除
            if (newestVedioList.size() >= total) {
                Log.e("ssss", "删除底部view");
                squareNewVideoAdapter.deleteFoolterView();
                squareNewVideoAdapter.notifyDataSetChanged();
            } else {
                squareNewVideoAdapter.notifyDataSetChanged();
            }
        }
        isFooterview = squareNewVideoAdapter.haveFooterView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onBannerError() {
        rxtextPcfl.refreshComplete();
    }

    @Override
    public void onSquareVideoError() {
        rxtextPcfl.refreshComplete();
    }

    @Override
    public void onNewestVideoError() {
        rxtextPcfl.refreshComplete();
    }

}
